package com.xn.app.muying;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.Constants;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.ToastUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class YanZhengActivity extends AppCompatActivity {
    private String TAG = this.getClass().getSimpleName();
    Button zc_next, huo_qu_yan_zheng;
    private Timer timer;// 计时器
    private int jishi = 60;
    EditText shou_ji_hao, yan_zheng_ma;
    String tag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhu_ce);
        zc_next = (Button) findViewById(R.id.zc_next);
        TextView yan_zheng_title = (TextView) findViewById(R.id.yan_zheng_title);
        huo_qu_yan_zheng = (Button) findViewById(R.id.huo_qu_yan_zheng);
        shou_ji_hao = (EditText) findViewById(R.id.shou_ji_hao);
        yan_zheng_ma = (EditText) findViewById(R.id.yan_zheng_ma);
        findViewById(R.id.guan_bi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tag = getIntent().getStringExtra("tag");
        if (TextUtils.equals(tag, "0")) {
            yan_zheng_title.setText("注册账号");
        } else if (TextUtils.equals(tag, "1")) {
            yan_zheng_title.setText("修改密码");
        } else if (TextUtils.equals(tag, "2")) {
            yan_zheng_title.setText("身份验证");
        }
        zc_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                String sj = shou_ji_hao.getText().toString();
                String yzm = yan_zheng_ma.getText().toString();
                if (!TextUtils.isEmpty(sj) && !TextUtils.isEmpty(yzm)) {
                    yanZheng(sj, yzm);
                } else {
                    ToastUtil.showToast(YanZhengActivity.this, "手机号和验证码不能为空");
                }

            }
        });
        huo_qu_yan_zheng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                String shou_ji = shou_ji_hao.getText().toString();
                if (TextUtils.isEmpty(shou_ji)) {
                    ToastUtil.showToast(YanZhengActivity.this, "手机号不能为空");
                } else {
                    huoQuYanZheng(shou_ji);
                }
            }
        });
    }

    AlertDialog yanzheng_dialog;

    void yanZheng(final String sj, final String yzm) {
        yanzheng_dialog = MyAlertDialog.ShowDialog(YanZhengActivity.this, R.layout.dialog_loading);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String yz = null;
                    if (TextUtils.equals(tag, "0")) {
                        yz = Constants.getStringByName(YanZhengActivity.this, "YanZheng");
                    } else if (TextUtils.equals(tag, "1")) {
                        yz = Constants.getStringByName(YanZhengActivity.this, "YanZheng1");
                    }else if (TextUtils.equals(tag, "2")) {
                        yz = Constants.getStringByName(YanZhengActivity.this, "YanZheng2");
                    }
                    Type type = new TypeToken<HashMap<String, String>>() {
                    }.getType();
                    HashMap<String, String> msg = new Gson().fromJson(yz, type);
                    HashMap<String, String> param = new HashMap<>();
                    param.put("token", msg.get("token"));
                    param.put("account", sj);
                    param.put("code", yzm);
                    String p = new Gson().toJson(param);
                    Log.i(TAG, "param==" + p);
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    Request request = new Request.Builder().url(APIMethod.YanZheng).put(formBody).build();
                    Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    //{"error":"invalid_grant","error_description":" 登录失败，用户名或密码错误！"}
                    Log.i(TAG, "code==" + code);
                    Log.i(TAG, bodys);
                    if (code == 204) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    AlertDialog zhuce_dialog;

    void huoQuYanZheng(final String shoujihao) {
        zhuce_dialog = MyAlertDialog.ShowDialog(YanZhengActivity.this, R.layout.dialog_loading);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HashMap<String, String> param = new HashMap<>();
                    if (TextUtils.equals(tag, "0")) {
                        param.put("function", "register");
                    } else if (TextUtils.equals(tag, "1")) {
                        param.put("function", "changepassword");
                    } else if (TextUtils.equals(tag, "2")) {
                        param.put("function", "forgetpassword");
                    }
                    param.put("mobile", shoujihao);
                    String p = new Gson().toJson(param);
                    Log.i(TAG, "param==" + p);
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(param));
                    Request request = new Request.Builder().url(APIMethod.HuoQuYanZhengMa).post(formBody).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    //{"error":"invalid_grant","error_description":" 登录失败，用户名或密码错误！"}
                    Log.i(TAG, "code==" + code);
                    Log.i(TAG, bodys);
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = bodys;
                        handler1.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.obj = bodys;
                        handler1.sendMessage(msg1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg1 = new Message();
                    msg1.what = 1;
                    handler1.sendMessage(msg1);
                }
            }
        }).start();
        jishi = 60;
        huo_qu_yan_zheng.setEnabled(false);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                timerHandler.sendEmptyMessage(jishi--);
            }
        }, 0, 1000);
    }

    @SuppressLint("HandlerLeak")
    private Handler timerHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                huo_qu_yan_zheng.setEnabled(true);
                huo_qu_yan_zheng.setText("获取验证码");
                timer.cancel();
            } else {
                huo_qu_yan_zheng.setText(msg.what + "秒后重发");
            }
        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    yanzheng_dialog.dismiss();
                    if (TextUtils.equals(tag, "0")) {
                        Intent intent = new Intent(YanZhengActivity.this, SheZhiMiMaActivity.class);
                        intent.putExtra("yanzheng", Constants.getStringByName(YanZhengActivity.this, "YanZheng"));
                        intent.putExtra("shoujihao", shou_ji_hao.getText().toString());
                        startActivity(intent);
                    } else if (TextUtils.equals(tag, "1")) {
                        Intent intent = new Intent(YanZhengActivity.this, ChongZhiMiMaActivity.class);
                        startActivity(intent);
                    } else if (TextUtils.equals(tag, "2")) {
                        Intent intent = new Intent(YanZhengActivity.this, WangJiMiMaActivity.class);
                        intent.putExtra("shoujihao", shou_ji_hao.getText().toString());
                        startActivity(intent);
                    }
                    finish();
                    break;
                case 1:
                    yanzheng_dialog.dismiss();
                    Type type = new TypeToken<HashMap<String, Object>>() {
                    }.getType();
                    HashMap<String, Object> errmsg = new Gson().fromJson(msg.obj.toString(), type);
                    Type type1 = new TypeToken<HashMap<String, String>>() {
                    }.getType();
                    HashMap<String, String> error = new Gson().fromJson(errmsg.get("error").toString(), type1);
                    ToastUtil.showToast(YanZhengActivity.this, error.get("message"));
                    break;
            }
        }
    };

    Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    zhuce_dialog.dismiss();
                    if (TextUtils.equals(tag, "0") ) {
                        Constants.setStringByName(YanZhengActivity.this, "YanZheng", msg.obj.toString());
                    } else if (TextUtils.equals(tag, "1")) {
                        Constants.setStringByName(YanZhengActivity.this, "YanZheng1", msg.obj.toString());
                    } else if (TextUtils.equals(tag, "2")) {
                        Constants.setStringByName(YanZhengActivity.this, "YanZheng2", msg.obj.toString());
                    }
                    ToastUtil.showToast(YanZhengActivity.this, "验证码已发送到你的手机，请注意查收！");
                    break;
                case 1:
                    zhuce_dialog.dismiss();
                    // {"result":null,"targetUrl":null,"success":false,"error":{"code":0,"message":"验证码已过期，请重新获取","details":null,"validationErrors":null},"unAuthorizedRequest":false,"__abp":true}
                    Type type = new TypeToken<HashMap<String, Object>>() {
                    }.getType();
                    HashMap<String, Object> errmsg = new Gson().fromJson(msg.obj.toString(), type);
                    Type type1 = new TypeToken<HashMap<String, String>>() {
                    }.getType();
                    HashMap<String, String> error = new Gson().fromJson(errmsg.get("error").toString(), type1);
                    ToastUtil.showToast(YanZhengActivity.this, error.get("message"));
                    break;
            }
        }
    };
}
